package jgl.vajra.management.widget.retrofithelper.rxsubscriber;

import android.content.DialogInterface;

import jgl.vajra.management.R;
import jgl.vajra.management.widget.bean.ServerErrorMessageBean;
import jgl.vajra.management.widget.interfaces.DialogFragmentStatesListener;
import jgl.vajra.management.widget.manager.LoadingFragmentManager;
import jgl.vajra.management.widget.mvvm.DisposableLifeCycleListener;
import jgl.vajra.management.widget.mvvm.view.AppActivityManager;
import jgl.vajra.management.widget.retrofithelper.rxexception.DefaultErrorBundle;
import jgl.vajra.management.widget.retrofithelper.rxexception.ErrorManager;
import jgl.vajra.management.widget.utils.UIUtils;

import java.lang.ref.WeakReference;

import androidx.fragment.app.FragmentActivity;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2016/11/24 0024.
 */
public abstract class ProgressObserver<T> implements Observer<T>, DialogFragmentStatesListener {
    private boolean isListenerDialogDismiss = true;
    private boolean isHandlerErrorCode = true;
    private boolean isUseBulr;
    private DisposableLifeCycleListener lifeCycleListener;
    private String loadMsg;
    private boolean isShowLoading;
    private WeakReference<FragmentActivity> appCompatActivity;
    //private LoadingDialogFragment fragment;
    // 是否是正常的取消显示dialog
    private boolean isRegularDialogDismiss;
    private Disposable mDisposable;
    private long showDialogLoadingTime;
    private long endTime;

    //  private IStateView iStateView;

    public ProgressObserver(FragmentActivity appCompatActivity, String loadMsg, boolean isShowLoading, DisposableLifeCycleListener lifeCycleListener) {
        //   this.iStateView = iStateView;
        if (isShowLoading)
            this.appCompatActivity = new WeakReference<>(appCompatActivity);
        this.loadMsg = loadMsg;
        this.isShowLoading = isShowLoading;
        this.lifeCycleListener = lifeCycleListener;
    }

    public ProgressObserver(String loadMsg, DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), loadMsg, true, lifeCycleListener);
    }

    public ProgressObserver(boolean isShowLoading, DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), isShowLoading, lifeCycleListener);
    }

    public ProgressObserver(boolean isShowLoading, boolean isListenerDialogDismiss, DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), isShowLoading, lifeCycleListener);
        this.isListenerDialogDismiss = isListenerDialogDismiss;
    }


    public ProgressObserver(DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), true, lifeCycleListener);
    }

    public ProgressObserver(FragmentActivity appCompatActivity, DisposableLifeCycleListener lifeCycleListener) {
        this(appCompatActivity, true, lifeCycleListener);

    }

    public ProgressObserver(FragmentActivity appCompatActivity, boolean isShowLoading, DisposableLifeCycleListener lifeCycleListener) {
        this(appCompatActivity, UIUtils.getString(R.string.net_processing_hint), isShowLoading, lifeCycleListener);
    }

    public ProgressObserver(FragmentActivity appCompatActivity, boolean isShowLoading, boolean isHandlerErrorCode, DisposableLifeCycleListener lifeCycleListener) {
        this(appCompatActivity, isShowLoading, lifeCycleListener);
        this.isHandlerErrorCode = isHandlerErrorCode;

    }

    public ProgressObserver(boolean isShowLoading, boolean isUseBulr, boolean isHandlerErrorCode, DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), isShowLoading, lifeCycleListener);
        this.isHandlerErrorCode = isHandlerErrorCode;
        this.isUseBulr = isUseBulr;

    }

    public ProgressObserver(boolean isShowLoading, boolean isUseBulr, boolean isHandlerErrorCode, boolean isListenerDialogDismiss, DisposableLifeCycleListener lifeCycleListener) {
        this(AppActivityManager.getAppActivityManager().currentActivity(), isShowLoading, lifeCycleListener);
        this.isHandlerErrorCode = isHandlerErrorCode;
        this.isUseBulr = isUseBulr;
        this.isListenerDialogDismiss = isListenerDialogDismiss;

    }

    @Override
    public void onError(Throwable e) {
        isRegularDialogDismiss = true;
        e.printStackTrace();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        mDisposable = null;
        ServerErrorMessageBean bean = null;
        if (isShowLoading && appCompatActivity != null) {
          /*  try {
                LoadingFragmentManager.getInstance().dismissLoadingDialog();
            } catch (Exception ee) {
                ee.printStackTrace();
            } finally {
                appCompatActivity = null;
                bean = ErrorManager.handleError(new DefaultErrorBundle((Exception) e), isHandlerErrorCode);
                _onError(bean.message, bean.status);
            }*/
            appCompatActivity = null;
            bean = ErrorManager.handleError(new DefaultErrorBundle((Exception) e), isHandlerErrorCode);
            _onError(bean.message, bean.code);
            try {
                LoadingFragmentManager.getInstance().dismissLoadingDialog();
            } catch (Exception ee) {
                ee.printStackTrace();
            } finally {

            }
        } else {
            bean = ErrorManager.handleError(new DefaultErrorBundle((Exception) e), isHandlerErrorCode);
            _onError(bean.message, bean.code);

        }


    }

    @Override
    public void onComplete() {

        if (endTime - showDialogLoadingTime < 1000) {
            UIUtils.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressCompleted();
                }
            }, 1000 - (endTime - showDialogLoadingTime));
        } else {
            progressCompleted();
        }


    }

    private void progressCompleted() {
        showDialogLoadingTime = 0;
        appCompatActivity = null;
        _onCompleted();
        // Logger.d("onComplete");
    }

    private void dismissLoadingDialog(final T t) {
      /*  endTime = System.currentTimeMillis();
        //  Logger.d(endTime - showDialogLoadingTime + "showDialogLoadingTime");
        if (endTime - showDialogLoadingTime < 1000) {
            UIUtils.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LoadingFragmentManager.getInstance().dismissLoadingDialog();
                }
            }, 1000 - (endTime - showDialogLoadingTime));
        } else {
            LoadingFragmentManager.getInstance().dismissLoadingDialog();
        }*/
        LoadingFragmentManager.getInstance().dismissLoadingDialog();

    }

    @Override
    public void onSubscribe(Disposable d) {
        if (lifeCycleListener != null) {
            if (lifeCycleListener.isStopRxJava()) {
                lifeCycleListener.addRxStop(d);
            } else {
                lifeCycleListener.addRxDestroy(d);
            }
        }
        this.mDisposable = d;
        isRegularDialogDismiss = false;
        if (isShowLoading && appCompatActivity != null) {
            showLoadingDialog(d);
        } else {
            _onSubscribe(d);
        }
    }


    private void showLoadingDialog(Disposable d) {
        if (appCompatActivity == null || appCompatActivity.get() == null) return;
        showDialogLoadingTime = 0;
        try {
            showDialogLoadingTime = System.currentTimeMillis();
            LoadingFragmentManager.getInstance().showLoadingDialog(appCompatActivity.get(), loadMsg);
            LoadingFragmentManager.getInstance().setUseBlur(isUseBulr);
            //监听dialog消失
            LoadingFragmentManager.getInstance().setDialogFragmentStatesListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            _onSubscribe(d);
        }
    }

    @Override
    public void onNext(T t) {
        isRegularDialogDismiss = true;
        // progressNext(t);
        if (isShowLoading && appCompatActivity != null) {
            progressNext(t);
            try {
                dismissLoadingDialog(t);
            } catch (Exception ee) {
                ee.printStackTrace();

            } finally {

            }
        } else {
            progressNext(t);
        }


    }

    private void progressNext(T t) {

        mDisposable = null;
        _onNext(t);
    }

    public void _onSubscribe(Disposable d) {

    }

    public void _onError(String errorMessage, int errorCode) {
        showDialogLoadingTime = 0;
    }

    public abstract void _onNext(T t);

    public void _onCompleted() {

    }

    @Override
    public void onDismiss(DialogInterface dialogInterface) {
        if (isRegularDialogDismiss && mDisposable == null) return;
        isRegularDialogDismiss = true;
        if (lifeCycleListener != null && isListenerDialogDismiss)
            lifeCycleListener.remove(mDisposable);
        mDisposable = null;

    }
}
